package com.hotitems_analysis

import java.util.Properties

import org.apache.kafka.clients.producer.{KafkaProducer, ProducerRecord}

import scala.io.BufferedSource

/**
  * @Description: TODO QQ1667847363
  * @author: xiao kun tai
  * @date:2021/11/30 23:03
  */
object KafkaProducerUtil {
  def main(args: Array[String]): Unit = {
    writeToKafka("hotitems")
  }

  def writeToKafka(topic:String): Unit ={
    val properties = new Properties()
    properties.setProperty("bootstrap.servers", "192.168.88.106:9092")
    properties.setProperty("key.serializer",
      "org.apache.kafka.common.serialization.StringSerializer")
    properties.setProperty("value.serializer",
      "org.apache.kafka.common.serialization.StringSerializer")

    val producer = new KafkaProducer[String,String](properties)

    //从文件读取数据，逐行写入kafka
    val filePath: String = "HotItemsAnalysis/src/main/resources/UserBehavior.csv"
    val bufferedSource: BufferedSource = io.Source.fromFile(filePath)
    for (line <- bufferedSource.getLines()) {
      val record= new ProducerRecord[String,String](topic,line)
      producer.send(record)
    }

    producer.close()
  }
}
